
package com.x52im.rbchat.logic.chat_friend.gift;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.x52im.mall.logic.score.RechargeActivity;
import com.eva.android.widget.alert.AlertDialog;
import com.eva.android.widget.WidgetUtils;
import com.eva.android.widget.WidgetUtils.ToastType;
import com.x52im.rbchat.MyApplication;
import com.x52im.rbchat.R;
import com.x52im.rbchat.logic.chat_friend.gift.model.GiftInPackageMeta;
import com.x52im.rbchat.logic.chat_friend.gift.model.GiftsMeta;
import com.x52im.rbchat.utils.PromtHelper;
import com.x52im.rbchat.utils.ActivityRequestCode;

/**
 * 礼品工具主UI实现类（本类目前将在{@link GiftsToolsPopupWindow}中
 * 作代理对象实现相关逻辑和功能）.
 * 
 * @author Jack Jiang(http://www.52im.net/space-uid-1.html)
 * @since 2.5
 * @see GiftsToolsPopupWindow
 */
public abstract class GiftsToolsUIWraper extends GiftsToolsUIWraperRoot
{
	private final static String TAG = GiftsToolsUIWraper.class.getSimpleName();
	
	/** 
	 * 是否仅用于查看背包的使用模式：true表示是，否则表示不是.
	 * 此模式下仅显示我的背包面板，应用场景目前是好友列表界面上。此模式下不对应任何好友。 */
	private boolean userForPackageOnly = false;
	
	/** 本工具面板根布局 */
	private RelativeLayout mainRL = null;
	/** 本工具的中间内容主布局 */
	private FrameLayout contentFL = null;
	
//	/**
//	 * 回调常量：充值积分
//	 */
//	public static final int GIFTS_RECHARGE_CIONS_RESULT = 998;
	
	//** 各种场景工具
	private GiftsPagerForSend pagerSend = null;
	private GiftsPagerForGet pagerGet = null;
	private GiftsPagerForPackage pagerPackage = null;
	
	//** 场景工具切换的按钮
	// 赠送礼品
	private RadioButton rdSend = null;
	// 索取礼品
	private RadioButton rdGet = null;
	// 我的背包
	private RadioButton rdPackage = null;
	
	// ** 通用组件
	// 我的当前积分
	private TextView viewScore = null;
	// 我的背包里的礼品数量
	private TextView viewMyGiftsCount = null;
	// 充值
	private Button btnChongZhi = null;
	// 兑换积分
	private Button btnDuihuan = null;

	//** 父Activity中传递过来的对象引用
	private Activity parentActivity = null;
	private String parentFriendUID = null;
	
	public GiftsToolsUIWraper(boolean userForPackageOnly
			, Activity parentActivity, String friendUID)
	{
		super(parentActivity);
		this.userForPackageOnly = userForPackageOnly;
		this.parentActivity = parentActivity;
		this.parentFriendUID = friendUID;
		init();
	}
	
	/**
	 * 核心初始化方法.
	 */
	private void init()
	{
		// *************************************** 初始化ui组件
		// 初始化布局
		mainRL = (RelativeLayout)findViewById(R.id.chatting_gift_main_popup_bottomMainRL);
		contentFL = (FrameLayout)findViewById(R.id.chatting_gift_main_popup_bottomContentFL);

		//** 初始化各工具面板
		if(!userForPackageOnly)
		{
			pagerSend = new GiftsPagerForSend(parentActivity, parentFriendUID, this){
				@Override
				protected void closeUIAfterSendIt()
				{
					closeUI();
				}
			};
			pagerGet = new GiftsPagerForGet(parentActivity, parentFriendUID);
		}
		pagerPackage = new GiftsPagerForPackage(parentActivity){
			/**
			 * 当前列表数据刷新时，本方法将携带当前礼品总数来通知ui实现类来刷新相应的ui显示。
			 */
			@Override
			protected void nofityForPackageGiftsNumChanged(int quantity)
			{
				//** 刷新我的背包里的礼品总数显示
				if(quantity > 0)
					viewMyGiftsCount.setVisibility(View.VISIBLE);
				else
					viewMyGiftsCount.setVisibility(View.GONE);
				viewMyGiftsCount.setText(String.valueOf(quantity));
			}
		};

		//** 初始化切换按钮
		rdSend = (RadioButton)findViewById(R.id.radio0);
		rdGet = (RadioButton)findViewById(R.id.radio1);
		rdPackage = (RadioButton)findViewById(R.id.radio2);
		if(userForPackageOnly)
		{
			rdSend.setVisibility(View.GONE);
			rdGet.setVisibility(View.GONE);
		}
		
		// TODO: 为了测试，暂时关闭了此用户类型判断代码 - 20180119 by JackJiang
//		// 自kchat2.5.1版（2014-04-17）起，规定普通用户没有索取功能
//		RosterElementEntity localRee = MyApplication.getInstance(parentActivity).getIMClientManager().getLocalUserInfo();
//		if(localRee != null
//				// 0 表示的是普通用户类型（用户类型存放在ex9字段中）
//				&& "0".equals(localRee.getUserType()))
//			rdGet.setVisibility(View.GONE);
		
		//** 初始化通用组件
		viewScore = (TextView)findViewById(R.id.chatting_gift_main_popup_scoreView);
		btnChongZhi = (Button)findViewById(R.id.chatting_gift_main_popup_chongzhiBtn);
		btnDuihuan = (Button)findViewById(R.id.chatting_gift_main_popup_duihuanBtn);
		viewMyGiftsCount = (TextView)findViewById(R.id.chatting_gift_main_popup_countView);

		// ** default visible
		if(!userForPackageOnly)
		{
//			pagerSend.setVisibility(View.GONE);
			pagerGet.setVisibility(View.GONE);
			pagerPackage.setVisibility(View.GONE);
		}

		//** 将工具面板放入到工具主界面上
		if(!userForPackageOnly)
		{
			contentFL.addView(pagerSend, new FrameLayout.LayoutParams(
				FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT ));
			contentFL.addView(pagerGet, new FrameLayout.LayoutParams(
				FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT ));
		}
		contentFL.addView(pagerPackage, new FrameLayout.LayoutParams(
				FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT ));

		//** 添加事件处理
		rdPackage.setOnCheckedChangeListener(createOnCheckedChangeListener(pagerPackage));
		if(!userForPackageOnly)
		{
			rdSend.setOnCheckedChangeListener(createOnCheckedChangeListener(pagerSend));
			rdGet.setOnCheckedChangeListener(createOnCheckedChangeListener(pagerGet));
		}
		else
			rdPackage.setChecked(true);
		
		//** 添加事件处理
		initListeners();
	}
	
	@Override
	protected void afterOnCheckedChange(View bindedView, boolean isChecked)
	{
		// 设置积分兑换按钮的可见性
		if(bindedView != null)
		{
			if(bindedView == pagerPackage)
			{
				if(isChecked)
					btnDuihuan.setVisibility(View.VISIBLE);
				else
					btnDuihuan.setVisibility(View.GONE);
			}
		}
	}
	
	private void initListeners()
	{
		btnChongZhi.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v)
			{
//				WidgetUtils.showToast(parentActivity, "点击了冲值按钮1！！！！！！！！", ToastType.INFO);
				parentActivity.startActivityForResult(
						new Intent(parentActivity, RechargeActivity.class), ActivityRequestCode.GIFTS_RECHARGE_CIONS_RESULT);
			}
		});
		
		btnDuihuan.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v)
			{
				if(GiftsProvider.getIntance().getGiftInPackageMeta(false, parentActivity).getGiftsInPackageData().size() > 0)
				{
					new AlertDialog.Builder(parentActivity)
					.setTitle(R.string.general_prompt)  
					.setMessage(parentActivity.getString(R.string.chatting_gift_score_exchang_hint))
					.setPositiveButton(R.string.general_yes, new DialogInterface.OnClickListener(){
						@Override
						public void onClick(DialogInterface dialog,int which)
						{
							new GiftsProvider.GiftToJifenAsyncTask(parentActivity){
								/**
								 * 成功处理后要调用的方法.
								 * 
								 * @param _currentScore Integer对象，本地用户的当前总积分数
								 */
								@Override
								protected void onPostExecute_sucess(int _currentScore)
								{
									//* 兑换成功的音效
									PromtHelper.toJifenPromt(parentActivity);

									//* 刷新积分在界面的显示
									refreshScore(_currentScore);

									//* 刷新背包数据（并列新ui显示）
									loadGiftInPackageMetaDataAsync(
											// 先清空我的背包
											GiftsProvider.getIntance().getGiftInPackageMeta(false, parentActivity).clearAll());

									//
									WidgetUtils.showToast(parentActivity
											, parentActivity.getString(R.string.chatting_gift_score_exchang_sucess)
											, ToastType.OK);
								}

								/**
								 * 服务端返回其它错误时要调用的方法.
								 * 
								 * @param _currentScore Integer对象，本地用户的当前总积分数
								 */
								@Override
								protected void onPostExecute_error(int _currentScore)
								{
									refreshScore(_currentScore);

									//
									WidgetUtils.showToast(parentActivity
											, parentActivity.getString(R.string.chatting_gift_score_exchang_faild)
											, ToastType.WARN);
								}

								private void refreshScore(int _currentScore)
								{
									//** 把数据刷新到UI上
									GiftsToolsUIWraper.this.onScoreLoaded(_currentScore);
								}
							}.execute();

						}
					}) 
					.setNegativeButton(parentActivity.getString(R.string.general_no), null)
					.show(); 
				}
				else
				{
					//
					WidgetUtils.showToast(parentActivity
							, parentActivity.getString(R.string.chatting_gift_score_exchang_packageisempty_hint)
							, ToastType.INFO);
				}
			}
		});
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onGiftsMetaLoaded(GiftsMeta senceMeta)
	{
		//** 把数据刷新到UI上
		if(senceMeta != null)
		{
			if(!userForPackageOnly)
			{
				//** 把数据刷新到UI上
				pagerSend.refreshUI(parentActivity, senceMeta);
				pagerGet.refreshUI(parentActivity, senceMeta);
			}

			Log.i(TAG, "礼品载入成功.");
		}
		else
		{
//			WidgetUtils.showToastLong(
//					parentActivity, MessageFormat.format(parentActivity.getString(R.string.chat_scence_tool_load_failure), senceMeta.getSenceName()), ToastType.WARN);
		}
	}
	
	@Override
	protected void onGiftInPackageMetaLoaded(GiftInPackageMeta senceMeta)
	{
		//** 把数据刷新到UI上
		if(senceMeta != null)
		{
			//** 把数据刷新到UI上
			pagerPackage.refreshUI(parentActivity, senceMeta);

			Log.i(TAG, "礼品包数据载入成功.");
		}
		else
		{
//			WidgetUtils.showToastLong(
//				parentActivity, MessageFormat.format(parentActivity.getString(R.string.chat_scence_tool_load_failure), senceMeta.getSenceName()), ToastType.WARN);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onScoreLoaded(int score)
	{
		viewScore.setText(String.valueOf(score));
		GiftsProvider.getIntance().setCurrentScore(score > 0 ? score : 0);
	}
	
	/**
	 * 本方法将在父Activity resume时被调用.
	 */
	@Override
	public void onParentResume()
	{
		// 在Activity处于前台时设置“收到礼品”的观察者，以便即时更新相关ui
		MyApplication.getInstance(parentActivity).getIMClientManager()
			.getTransDataListener().setReceivedGiftObserverForGiftToolsUI(pagerPackage.getReceivedGiftObserverForGiftToolsUI());
	}
	/**
	 * 本方法将在父Activity pause时被调用.
	 */
	@Override
	public void onParentPause()
	{
		// 在Activity处于后台时取消设置“收到礼品”的观察者
		MyApplication.getInstance(parentActivity).getIMClientManager()
			.getTransDataListener().setReceivedGiftObserverForGiftToolsUI(null);
	}
}
